/******************************************************************************
 * Copyright (c) 2014 - 2016. Danlu.com Co.Ltd. All rights reserved.          *
 ******************************************************************************/

package cn.com.dhc.danlu.widget.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.yiji.www.frameworks.utils.DensityUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.goods.GoodInfoActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.bus.BaseEvent;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.home.GoodsInfoHolder;
import cn.com.dhc.danlu.widget.home.HomeListView;
import cn.com.dhc.danlu.widget.home.PromotionView;
import cn.com.dhc.danlu.widget.home.PurchaseView;
import cn.com.hd.mall.web.webservices.entity.request.shoppingcart.AddShoppingCartRequest;
import cn.com.hd.mall.web.webservices.entity.response.merch.base.BaseMerchListModel;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.AddShoppingcartResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;
import static cn.com.dhc.danlu.util.CommonConst.ShoppingCarModel.ADD_SHOPPINGCAR_ERROR_2;
import static cn.com.dhc.danlu.util.CommonConst.ShoppingCarModel.ADD_SHOPPINGCAR_ERROR_3;
import static cn.com.dhc.danlu.util.CommonConst.ShoppingCarModel.ADD_SHOPPINGCAR_ERROR_4;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">wuhaiyang@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2016-08-04 16:29<br/>
 *
 * <p>
 * 通用adapter 首页 、采购、常购
 * </p>
 */
public class GeneralGoodsAdapter extends MyBaseAdapter {
    public static final String REFRESH_BADGE_SHOPCARD = "adapter_refresh_shopcart_badge";
    private final ArrayMap<Integer, GoodsCacheModel> mCacheModelArrayMap = new ArrayMap<>();
    private ListType mListType;

    public GeneralGoodsAdapter(Context context, ListType listType) {
        super(context);
        this.mListType = listType;
    }

    @Override
    public void refreshData(List datas) {
        if (null == datas) {
            datas = new ArrayList();
        }
        super.refreshData(datas);
        mCacheModelArrayMap.clear();
    }

    @Override
    public void appendData(List datas) {
        super.appendData(datas);
        mCacheModelArrayMap.clear();
    }

    @Override
    protected View createView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder mHolder;
        if (null == convertView) {
            convertView = mInflater.inflate(R.layout.dl_item_home_goods_info, parent, false);
            mHolder = new ViewHolder(convertView);
            convertView.setTag(mHolder);
        } else {
            mHolder = (ViewHolder) convertView.getTag();
        }
        final BaseMerchListModel model = (BaseMerchListModel) getItem(position);
        GoodsCacheModel cacheModel = mCacheModelArrayMap.get(position);

        int purchaseCount = 1;
        boolean isShowPurchasView = false;
        boolean isFold = true;
        if (null != cacheModel) {
            //获取之前的记录
            purchaseCount = cacheModel.mPurchaseCount;
            isShowPurchasView = cacheModel.isShowPurchaseView;
            isFold = cacheModel.isFold;
        }

        if (purchaseCount == 1 && !TextUtils.isEmpty(model.getMinSaleNumber())) {
            purchaseCount = Integer.valueOf(model.getMinSaleNumber());
        }

        //刷新商品视图
        mHolder.mGoodsInfoHolder.refreshView(model, mListType, new GoodsInfoHolder.OnShopClickListener() {
            @Override
            public void onClick(View v, float rawY) {
                float diff = CommonUtils.getScreenHeight(getContext()) - rawY - DensityUtils.dip2px(getContext(), 53);
                float origin = DensityUtils.dip2px(getContext(), 100) + mHolder.mPromotionsLayout.getMeasuredHeight() + (mHolder.mPromotionsLayout.getMeasuredHeight() == 0 ? 0 : DensityUtils.dip2px(getContext(), 17));
                //监听购物车按钮实现 显示/隐藏
                int visibility = mHolder.mPurchaseView.getVisibility();
                GoodsCacheModel cacheModel = mCacheModelArrayMap.get(position);
                if (null == cacheModel) {
                    cacheModel = new GoodsCacheModel();
                }
                if (visibility == View.VISIBLE) {
                    mHolder.mPurchaseView.setVisibility(View.GONE);
                    mHolder.mPurchaseView.setDefaultCount(Integer.parseInt(model.getMinSaleNumber()));
                    //刷新缓存
                    cacheModel.setPurchaseCount(Integer.parseInt(model.getMinSaleNumber()));
                    cacheModel.setIsShowPurchaseView(false);
                } else {
                    cacheModel.setIsShowPurchaseView(true);
                    mHolder.mPurchaseView.setVisibility(View.VISIBLE);
                }
                mCacheModelArrayMap.put(position, cacheModel);
                if (origin > diff && mHolder.mPurchaseView.getVisibility() == View.VISIBLE) {
                    int moveHeight = (int) (origin - diff);
                    if (parent instanceof AbsListView) {
                        AbsListView listView = (AbsListView) parent;
                        //滚动到指定视图可见的位置 比较麻烦
                        scrollView(listView, moveHeight);
                    } else if (parent instanceof HomeListView) {
                        //首页视图相关
                        HomeListView listView = (HomeListView) parent;
                        scrollView(listView, moveHeight);
                    }
                }
            }
        });

        //刷新促销信息视图
        if (null == model.getPromotionList() || model.getPromotionList().isEmpty()) {
            mHolder.mPromotionsLayout.setVisibility(View.GONE);
        } else {
            mHolder.mPromotionsLayout.setVisibility(View.VISIBLE);
            mHolder.mPromotionsLayout.bindPromotion(model.getPromotionList(), isFold);
            mHolder.mPromotionsLayout.setOnFoldListener(new PromotionView.OnFoldListener() {
                @Override
                public void onFoldAction(boolean fold) {
                    //监听折叠事件
                    GoodsCacheModel cacheModel = mCacheModelArrayMap.get(position);
                    if (null == cacheModel) {
                        cacheModel = new GoodsCacheModel();
                    }
                    cacheModel.setIsFold(!fold);
                    mCacheModelArrayMap.put(position, cacheModel);
                }
            });
        }

        //刷新购物车视图
        if (isShowPurchasView) {
            mHolder.mPurchaseView.setVisibility(View.VISIBLE);
        } else {
            mHolder.mPurchaseView.setVisibility(View.GONE);
        }
        mHolder.mPurchaseView.setOnSureClickListener(new PurchaseView.OnSureClickListener() {
            @Override
            public void onClick(View v, int count) {
                //  网络请求加入购物车逻辑
                addGoodsToShop(model, count, mHolder.mPurchaseView, position);
            }

            @Override
            public void onCountChanged(int count) {
                // 购物车 数量变化监听
                GoodsCacheModel cacheModel = mCacheModelArrayMap.get(position);
                if (null == cacheModel) {
                    cacheModel = new GoodsCacheModel();
                }
                cacheModel.setPurchaseCount(count);
                mCacheModelArrayMap.put(position, cacheModel);
            }
        });

        mHolder.mPurchaseView.setDefaultCount(purchaseCount);
        if (!TextUtils.isEmpty(model.getMinSaleNumber())) {
            mHolder.mPurchaseView.setMinCount(Integer.valueOf(model.getMinSaleNumber()));
        }
        if (mListType != ListType.often_buy_hot && mListType != ListType.often_buy_off) {
            // 我的唱够中热卖中的商品和已下架的商品 点击事件单独抽离出来 ： 常购 listview和itemview 点击事件冲突
            mHolder.llGoodsContainer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(model.getMerchId())) {
                        Intent intent = new Intent(mInflater.getContext(), GoodInfoActivity.class);
                        intent.putExtra(CommonConst.IntentKey.MERCHANDISE_ID, model.getMerchId());
                        mInflater.getContext().startActivity(intent);
                    }
                }
            });
        }
        if (mListType != ListType.recommended || ListType.sale_promotion != mListType) {
            convertView.setAnimation(AnimationUtils.loadAnimation(mInflater.getContext(), R.anim.alpha_in));
        }
        return convertView;
    }

    @Override
    public int getCount() {
        return super.getCount();
    }

    private Context getContext() {
        return mInflater.getContext();
    }

    private void scrollView(final View listView, final int i) {
        View view = listView;
        ViewParent parentTmp = listView.getParent();
        while (parentTmp != null) {
            if (parentTmp instanceof ScrollView) {
                view = (ScrollView) parentTmp;
                break;
            }
            parentTmp = parentTmp.getParent();
        }
        final View finalView = view;
        if (view instanceof AbsListView) {
            view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ((AbsListView) finalView).smoothScrollBy(i, 500);
                }
            }, 50);
        } else if (view instanceof ScrollView) {
            view.postDelayed(new Runnable() {
                @Override
                public void run() {
                    ((ScrollView) finalView).smoothScrollBy(0, i);
                }
            }, 50);
        }
    }

    private void addGoodsToShop(final BaseMerchListModel model, long count, final PurchaseView purchaseView, final int position) {
        AddShoppingCartRequest request = new AddShoppingCartRequest();
        request.setToken(agent.getToken());
        request.setMerchCount(count + "");
        request.setMerchId(model.getMerchId());
        request.setSellerId(model.getSellerId());
        request.setSellerName(model.getSellerName());
        agent.getApi()
                .addShoppingCartNew(request)
                .compose(OperatorUtils.<AddShoppingcartResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<AddShoppingcartResponse>(getContext(), R.string.loading_common_msg) {
                    @Override
                    protected void onSuccess(AddShoppingcartResponse res) {
                        ToastUtil.getInstance().show(R.string.add_shopping_cart_success);
                        BaseEvent<String> baseEvent = new BaseEvent<>();
                        baseEvent.setEventFrom(REFRESH_BADGE_SHOPCARD);
                        EventBus.getDefault().post(baseEvent);
                        int i = Integer.parseInt(model.getMinSaleNumber());
                        purchaseView.setDefaultCount(i);
                        GoodsCacheModel goodsCacheModel = mCacheModelArrayMap.get(position);
                        if (null == goodsCacheModel) {
                            goodsCacheModel = new GoodsCacheModel();
                        }
                        goodsCacheModel.setPurchaseCount(i);
                        mCacheModelArrayMap.put(position, goodsCacheModel);
                        purchaseView.setVisibility(View.GONE);
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        if (code.equals(ADD_SHOPPINGCAR_ERROR_2)) {
                            return getContext().getString(R.string.add_shopping_cart_error_3);
                        } else if (code.equals(ADD_SHOPPINGCAR_ERROR_3)) {
                            return getContext().getString(R.string.add_shopping_cart_error_2);
                        } else if (code.equals(ADD_SHOPPINGCAR_ERROR_4)) {
                            return getContext().getString(R.string.add_shopping_cart_error_4);
                        } else {
                            return "添加购物车失败";
                        }
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    public enum ListType {
        sale_promotion,
        recommended,
        often_buy_hot,
        often_buy_off,
        merchlist
    }

    private static class ViewHolder {
        GoodsInfoHolder mGoodsInfoHolder;
        PromotionView mPromotionsLayout;
        PurchaseView mPurchaseView;
        LinearLayout llGoodsContainer;

        ViewHolder(View view) {
            llGoodsContainer = (LinearLayout) view.findViewById(R.id.ll_goods_container);
            mPromotionsLayout = (PromotionView) view.findViewById(R.id.pl_container);
            mPurchaseView = (PurchaseView) view.findViewById(R.id.pv_buy);
            mGoodsInfoHolder = new GoodsInfoHolder(view);
        }
    }

    private static class GoodsCacheModel {
        //当前购买数量
        int mPurchaseCount = 1;
        //当前是否显示了购买视图
        boolean isShowPurchaseView = false;
        //当前促销信息是否处于折叠状态
        boolean isFold = true;

        public long getPurchaseCount() {
            return mPurchaseCount;
        }

        void setPurchaseCount(int purchaseCount) {
            mPurchaseCount = purchaseCount;
        }

        public boolean isShowPurchaseView() {
            return isShowPurchaseView;
        }

        void setIsShowPurchaseView(boolean isShowPurchaseView) {
            this.isShowPurchaseView = isShowPurchaseView;
        }

        public boolean isFold() {
            return isFold;
        }

        void setIsFold(boolean isFold) {
            this.isFold = isFold;
        }
    }
}
